const express = require('express');
const router = express.Router();
const { jwtCheck } = require('../../utils/jwt')
const sha256 = require('../../utils/sha256');
const conn = require('../../db/mysql');
const fs = require('fs');
const path = require('path');
const util = require("util");

/**
 * 获取所有用户信息
 * @summary 获取所有用户信息
 * @route GET /users
 * @group USER
 * @returns {object} 200 - {code: 200,msg: "获取成功",type: "success",data: {}}
 * @returns {Error}  default - {code:400,msg: "获取成功",type: "fail",data:{err:object}}
 * @security JWT
 */
router.get('/userById', (req, res, next) => {
    let token = jwtCheck(req.headers.authorization);
    const sql = `SELECT * FROM user where user_id='${token.msg.account}'`;
    let dataTemplent = {
        code: 200,
        type: "success",
        msg: "查询成功",
        data: {}
    }
    conn.query(sql, (err, result) => {
        if (err) {
            dataTemplent.code = 400;
            dataTemplent.type = "fail";
            dataTemplent.msg = "查询失败";
        } else {
            const filePath = path.join(__dirname, '../../public/upload', result[0].avatarurl);
            const imageData = fs.readFileSync(filePath);
            const imageBase64 = imageData.toString("base64");
            const imagePrefix = "data:image/png;base64,";
            dataTemplent.data = result;
            dataTemplent.data[0].avatarurl = imagePrefix + imageBase64;
        }
        res.send(dataTemplent);
    });
});
/**
 * 获取用户信息（分页）
 * @summary 获取用户信息（分页）
 * @route GET /user
 * @group USER
 * @param {string} username.query - 人名
 * @param {number} pageSize.query.required - 分页大小
 * @param {number} page.query.required - 页码
 * @returns {object} 200 - {code: 200,msg: "获取成功",type: "success",data: {}}
 * @returns {Error}  default - {code:400,msg: "获取成功",type: "fail",data:{err:object}}
 * @security JWT
 */
router.get('/user', (req, res, next) => {
    let userName = req.query.username;
    let pageSize = req.query.pageSize; // 页大小
    let pageCurrent = req.query.page; // 当前页
    let start = (pageCurrent - 1) * pageSize; // 起始位置
    let sql = "";
    if (userName) {
        sql = `SELECT *  FROM user WHERE username LIKE '%${userName}%' LIMIT ${start},${pageSize}`;
    } else {
        sql = `SELECT *  FROM user LIMIT ${start},${pageSize}`;
    }
    let dataTemplent = {
        code: 200,
        msg: "查询成功",
        type: "success",
        data: {}
    }
    conn.query(sql, (err, result) => {
        if (err) throw err;
        let list = result
        conn.query(`SELECT COUNT(*) AS total FROM user`, (err, result1) => {
            if (err) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "查询失败";

            }
            else {
                let obj = {
                    pageSize: pageSize,
                    pageCurrent: pageCurrent,
                    total: result1[0].total,
                    list: list
                }
                dataTemplent.data = obj;
            }
            res.send(dataTemplent);
        })
    })
});
/**
 * 新增用户
 * @summary 新增用户
 * @route POST /user
 * @group USER
 * @param {string} userInfo.body.required - account、username、password、avatarurl
 * @returns {object} 200 - {code: 200,msg: "新增成功",type: "success",data: {}}
 * @returns {Error}  default - {code:400,msg: "新增失败",type: "fail",data:{err:object}}
 * @security JWT
 */
router.post('/user', (req, res, next) => {
    let params = req.body;
    let dataTemplent = {
        code: 200,
        msg: "新增成功",
        type: "success",
        data: {}
    }
    if (params) {
        const password = sha256(params.password);
        const sql = `INSERT INTO user VALUES('0','${params.account}','${params.username}','${password}','${params.avatarurl}');`;
        conn.query(sql, (err, result) => {
            if (err) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "新增失败";

            } else {
                dataTemplent.data = { id: result.insertId };
            }
            res.send(dataTemplent);
        });
    }
});
/**
 * 修改用户
 * @summary 修改用户
 * @route PUT /user
 * @group USER
 * @param {string} userInfo.body.required - account、username、password、avatarurl
 * @returns {object} 200 - {code: 200,msg: "新增成功",type: "success",data: {}}
 * @returns {Error}  default - {code:400,msg: "新增失败",type: "fail",data:{err:object}}
 * @security JWT
 */
router.put('/user', (req, res, next) => {
    let token = jwtCheck(req.headers.authorization) || {};
    let params = req.body;
    let dataTemplent = {
        code: 200,
        type: "success",
        msg: "修改成功",
        data: {}
    }
    let id = token.msg.account;
    let avatarUrl = '';
    let usernameSql = params.username ? `username='${params.username}'` : '';
    avatarUrl = id + Date.now() + '.png';
    let avatarurlSql = params.avatarurl ? `,avatarurl='${avatarUrl}'` : '';
    if (params) {
        const sql = `UPDATE user set ${usernameSql} ${avatarurlSql}  WHERE user_id='${id}';`;
        conn.query(sql, (err, result) => {
            if (err) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "修改失败";
            } else {
                if (params.avatarurl) {
                    const filePath = path.join(__dirname, '../../public/upload', avatarUrl);
                    const base64 = params.avatarurl.replace(/^data:image\/\w+;base64,/, "");
                    const dataBuffer = Buffer.from(base64, 'base64');
                    fs.writeFile(filePath, dataBuffer, function (err) {
                        if (err) {
                            // console.log(err);
                        } else {
                            // console.log('写入成功！');
                        }
                    })
                    dataTemplent.data = { avatarurl: avatarUrl };
                }
                res.send(dataTemplent);
            }
        });
    } else {
        dataTemplent.type = "fail";
        dataTemplent.msg = "修改失败";
        dataTemplent.code = 400;
        res.send(dataTemplent);
    }
});
/**
 * 用户删除
 * @summary 用户删除
 * @route DELETE /user
 * @group USER
 * @param {string} id.body.required -用户id
 * @returns {object} 200 - {code: 200,msg: "删除成功",type: "success",data: {}}
 * @returns {Error}  default - {code:400,msg: "删除失败",type: "fail",data:{err:object}}
 * @security JWT
 */
router.delete('/user', (req, res, next) => {
    let params = req.body;
    let dataTemplent = {
        code: 200,
        type: "success",
        msg: "删除成功",
        data: {}
    }
    if (params) {
        const sql = `DELETE FROM user WHERE user_id='${params.id}';`;
        conn.query(sql, (err, result) => {
            if (err) {
                dataTemplent.code = 400;
                dataTemplent.type = "fail";
                dataTemplent.msg = "删除失败";
            } else {
                dataTemplent.data = { affectedRows: result.affectedRows };
            }
            res.send(dataTemplent);
        });
    }
});
module.exports = router;